package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.entity.MobilePermission;
import com.xmy.cultivate.entity.MobileRolePermission;
import com.xmy.cultivate.service.IMobileRolePermissionService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-06-26
 */
@RestController
@RequestMapping("/api/mobileRolePermission")
public class MobileRolePermissionController {
    @Autowired
    IMobileRolePermissionService iMobileRolePermissionService;

    @ApiOperation("通过角色查询权限")
    @GetMapping("")
    public Result getRolePermissionAllByStaffId(@RequestParam(value = "roleId", required = false) String roleId) {
        if (StringUtils.isBlank(roleId)) {
            return new Result(Code.GET_OK, null, Code.GET_OK_MSG);
        }
        List<Long> staffPermissionList = iMobileRolePermissionService.getRolePermissionByRoleId(roleId);
        return new Result(Code.GET_OK, staffPermissionList, Code.GET_OK_MSG);
    }

    @ApiOperation("添加或修改角色权限")
    @PostMapping()
    public Result saveOrUpdate(@RequestBody Map reMap) {
        String roleId = (String) reMap.get("roleId");
        List<Object> rolePermissionIdList = (List<Object>) reMap.get("rolePermissionIdList");

        iMobileRolePermissionService.remove(new QueryWrapper<MobileRolePermission>().eq("role_id", roleId));

        for (Object permissionId : rolePermissionIdList) {
            MobileRolePermission mobileRolePermission = new MobileRolePermission();
            mobileRolePermission.setRoleId(Long.parseLong(roleId));
            mobileRolePermission.setPermissionId(Long.parseLong((String) permissionId));
            iMobileRolePermissionService.save(mobileRolePermission);
        }

        return new Result(Code.OK, "", Code.OK_MSG);
    }

}
